<template>
  <div style="width: 100%; height: 100%">

    <div :style="{height: (contentHeight*0.90)+'px'}">
      <vxe-grid ref="tableRef" v-bind="gridOptions"     @sortChange="sortChangeEvent">
        <template #toolbar_buttons>
          <!--        <Button type="primary" @click="handleCreate">新增</Button>-->
          <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD" v-if="userName == '蔡志杰' ||userName == 'manage'">
            <Button class="m-3" :loading="loading"  size="small" > 导入关联物料 </Button>
          </ImpExcel>
          <Button type="primary" @click="handleCreate" :loading="loading" style="margin-left: 5px" size="small">同步齐套</Button>
        </template>
        <template #action="{ row }">
          <TableAction outside :actions="[
          {
              label:'查看',
              onClick: handleEdit.bind(null, row),
          },
          {
              label:'备注',
              icon: 'clarity:note-edit-line',
              onClick: editFn.bind(null, row),
          },

        ]
        " />
        </template>
        <template #queLiaos_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.queLiaos"  status="error"></vxe-text>
        </template>
        <template #biaoTouNum_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.biaoTouNum"></vxe-text>
        </template>
        <template #chuanDaiNum_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.chuanDaiNum"></vxe-text>
        </template>
        <template #baoZhuanNum_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.baoZhuanNum"></vxe-text>
        </template>
        <template #totalUnDo_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.totalUnDo"></vxe-text>
        </template>

        <template #qiTaoNum_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.qiTaoNum"></vxe-text>
        </template>

        <template #izWenjianUp_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.izWenjianUp"></vxe-text>
        </template>
        <template #note_slot="{ row }">
          <vxe-text  :content="row.note" :status="getNoteValue(row).status"></vxe-text>
        </template>
        <template #isQiTao_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.isQiTaoText" :status="getTotalUnDoValue(row).status"></vxe-text>
        </template>
        <template #isQueLiao_slot="{ row }">
          <vxe-text :loading="item_loading" :content="row.isQueLiaoText" :status="getQueLiaoValue(row).status"></vxe-text>
        </template>

      </vxe-grid>
    </div>
    <FormModal @register="register" @success="handleSuccess" />

    <vxe-modal v-model="applyViewShow" title="请输入备注信息" :width="600" :height="400" esc-closable>
      <div>
        <vxe-form
          ref="formRef"
          :data="formData"
          size="small"
          :rules="formRules"
          @submit="submitEvent"
          @reset="resetEvent">

          <vxe-form-item title="备注" field="note" span="24" :item-render="{}">
            <template #default="params">
              <vxe-textarea v-model="formData.note" placeholder="请输入备注"></vxe-textarea>
            </template>

          </vxe-form-item>
          <vxe-form-item align="center" span="24" :item-render="{}">
            <template #default>
              <vxe-button type="submit" status="primary" content="提交"></vxe-button>
              <vxe-button type="reset" content="重置"></vxe-button>
            </template>
          </vxe-form-item>

        </vxe-form>
      </div>
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import util from '@/utils/util';
import { useUserStore } from '@/store/modules/user';

import { BasicTable, useTable, TableAction } from '@/components/Table';
import { VxeUI,VxeDatePickerPropTypes,VxeDatePicker } from 'vxe-pc-ui'

import { useDrawer } from '@/components/Drawer';
import {computed, onMounted, reactive, ref} from 'vue';

import FormModal from './FormModal.vue';

import { columns, searchFormSchema,vxeTableColumns,vxeTableFormSchema } from './role.data';
import { useMessage } from "@/hooks/web/useMessage";
import {Button, Modal} from 'ant-design-vue';
import { useGo } from "@/hooks/web/usePage";
import {ImpExcel} from "@/components/Excel";
import {importOemMaterialRef, pmcOemList,pmcOemNote,getQueLiaos,baogongQueryList,pmcAutoSync,getQiTaoNum,pmcWenjianList} from '@/api/heng/stock';
import {useRouter} from "vue-router";
// 校验
VxeUI.validators.add('ValidMobile', {
  formItemValidatorMethod ({ itemValue }) {
    if (!itemValue) {
      return new Error('请输入备注')
    }
  }
})


const router = useRouter();

const go = useGo();
const contentHeight = ref(window.innerHeight);

const userStore = useUserStore();
let userName = userStore.getUserInfo?.userName;

defineOptions({ name: 'ywDeptList' });
const { createMessage } = useMessage();

// const [register, { openModal, closeModal }] = useModal();
const [register, { openDrawer,closeDrawer }] = useDrawer();

const loading=ref(false);
const item_loading=ref(false);

const msgList = ref([]);
const applyViewShow = ref(false);

const isQiTao=computed(()=>router.currentRoute.value.params.isQiTao) ;

const izResolveType=computed(()=>router.currentRoute.value.params.izResolveType) ;



const buMenName=ref("oem");

const tableRef = ref<VxeGridInstance>();

const sortColumn=ref("");//字段名称

const sortOrder=ref(""); // 排序类型 asc desc
const formData=ref({note:""});

const formRules = reactive<VxeFormPropTypes.Rules>({
  note: [
    { required: true, validator: 'ValidMobile' }
  ]

})

if(isQiTao.value){
  // vxeTableFormSchema.splice(1,1)
  vxeTableFormSchema[1].visible=false;
  // vxeTableForm=vxeTableFormSchema.splice(1,1);
}else{
  vxeTableFormSchema[1].span=4;
  vxeTableFormSchema[1].visible=true;

}
//console.log("--izResolveType.value:",router.currentRoute.value)

if(izResolveType.value){
  vxeTableFormSchema[1].visible=false;
  vxeTableFormSchema[2].visible=true;
  vxeTableFormSchema[3].visible=false;

}

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  sortConfig:{
    remote: true,
  },
  exportConfig:{},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
        // return new Promise((resolve,reject) => {
        //   findPageList(page, form, filters).then(res=>{
        //     resolve(res);
        //     getQueLiaosFn(res)
        //   }).catch(err=>{
        //     reject(err);
        //   })
        // });
      },
      querySuccess:  (e)=>{
        // console.log("----querySuccess::",e)
        getQueLiaosFn(e)
      }
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {
    sortColumn:sortColumn.value,
    sortOrder:sortOrder.value,
    buMenName:buMenName.value
  };

  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.values[0];
      const value2 = e.datas[0];
      let field = e.field;
      let result=null;
      if(value!=null){
        result=value;
      }
      if(value2!=null){
        result=value2;
      }
      json[field ] = result;

    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList

  if(isQiTao.value!=null&&isQiTao.value!=undefined){
    if(json.isQiTao==null||json.isQiTao==undefined){
      if(isQiTao.value){
        json.isQiTao=1
      }else{
        json.isQiTao=0

      }
    }
  }


  return pmcOemList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}


function sortChangeEvent({ field, order }){
  // console.log("--field: ", field);
  // console.log("--order: ", order);
  sortColumn.value = field;
  sortOrder.value = order;
  tableRef.value?.commitProxy('reload');
}

function handleCreate() {

  loading.value = true;
  pmcAutoSync({
    buMenName:buMenName.value
  }).then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      tableRef.value?.commitProxy('reload');
    }else{
      createMessage.error("失败："+res.message);
    }
  }).finally(()=>{
    loading.value = false;
  })

}

onMounted(() => {

})


function handleEdit(record: Recordable) {
  record.isUpdate=true;
  openDrawer(true, record);

}

function editFn(record: Recordable) {

  formData.value.note=record.note||"";
  formData.value.biaoShiHao=record.biaoShiHao;
  applyViewShow.value=true;

}


function handleDelete(record: Recordable) {

}

function handleSuccess() {
  tableRef.value.commitProxy('query');

}


function applyViewOpen() {
  applyViewShow.value = true;
}


/**
 * 获取齐套的状态和颜色
 * @param row
 */
function getTotalUnDoValue(row){
  let text="",status="";
  if(row.totalUnDo!=null){
    if(row.totalUnDo<=0){
      text="完成";
      status="success";
    }else if(row.totalUnDo>0){
      text="未完成";
      status="error";
    }
  }
  return {text,status};


}



function getQueLiaoValue(row){
  let text="",status="";
  if(row.queLiaos){
    text="缺料";
    status="error";
  }else{
    text="齐套";
    status="success";
  }
  return {text,status};


}


function getNoteValue(row){
  let text="",status="";
  if(row.note&&row.note=="齐"){
    status="success";
  }else{
    status="error";
  }
  return {text,status};


}

/**
 * 查询缺料情况
 */

function getQueLiaosFn(e) {
  // console.log("--getQueLiaosFn:",res);
  item_loading.value = true;
  let list = e.response.data.list;
  let id_arr=[];//标识号数组
  let batch_arr=[];//批次号数组

  for(let i=0;i<list.length;i++){
    let item=list[i];
    id_arr.push(item.biaoShiHao);
    batch_arr.push(item.piCiHao);
  }
  //console.log("--tableData:",e.$grid)
  if(id_arr.length>0){

    let q_json={
      biaoShiHaoIn:id_arr,
      buMenName:buMenName.value,
    }
    Promise.all([
      getQueLiaos(q_json),
      baogongQueryList(q_json),
      getQiTaoNum(q_json),
      pmcWenjianList(batch_arr)
    ]).then(e=>{
      let data1=e[0].data;
      let data2=e[1].data;
      let data3=e[2].data;
      let data4=e[3].data;

      data2.forEach((item2)=>{
        for(let key in data1){
          if(item2.biaoShiHao==key){
            item2.queLiaos=data1[key];
          }
        }
        for(let key in data3){
          if(item2.biaoShiHao==key){
            item2.qiTaoNum=data3[key];
          }
        }

      });
      for(let i=0;i<list.length;i++) {
        let item = list[i];
        for(let a=0;a<data2.length;a++){
          let item2 = data2[a];

          if(item.biaoShiHao==item2.biaoShiHao){
            item.queLiaos=item2.queLiaos;
            item.qiTaoNum=item2.qiTaoNum;
            item.chengpingNum=item2.chengpingNum;//成品组装
            if(item2.chengpingNum){
              item.biaoTouNum=item2.chengpingNum;//表头组装
              item.chuanDaiNum=item2.chengpingNum;//表头组装
            }else{
              item.biaoTouNum=item2.biaoTouNum;//表头组装
              item.chuanDaiNum=item2.chuanDaiNum;//穿带
            }
            item.baoZhuanNum=item2.baoZhuanNum;//包装
            item.totalUnDo=item.xiaoShouShuLiang-item2.baoZhuanNum;
          }

          for(let key in data4){
            if(item.piCiHao==data4[key].piCiHao){
              item.izWenjianUp="已上传";
            }
          }
        };

        item.isQiTaoText=getTotalUnDoValue(item).text;
        item.isQueLiaoText=getQueLiaoValue(item).text;


      }
     // e.$grid.loadData(list)

    }).finally(()=>{
      item_loading.value = false;
    });
  }
}




/**
 * 导入excel
 *
 */
const arrHeader = [
  {
    key: 'no',
    value: '物料编码',
  },
  {
    key: 'name',
    value: '物料名称',
  },
  {
    key: 'pno',
    value: '上级编号',
  }
];

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  // let list = [];
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      arrHeader.forEach((e) => {
        if (e.value == key) {
          json[e.key] = r[key];
        }
      });
    }
    data.list.push(json);
  });
  return data;
}

function excelSuccessFn(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除第一行
  // results.shift();
  let data = changeSubmitArr(results);
  // console.log(data);
  // return;
  loading.value = true;
  importOemMaterialRef({buMenName:buMenName.value,list:data.list})
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {

          msgList.value = res.data;
          applyViewOpen();
        } else {
          createMessage.success('导入成功!');
          tableRef.value.commitProxy('reload');
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}


function submitEvent({data}) {
 // console.log("--submitEvent:",data);
  let json={
    biaoShiHao: formData.value.biaoShiHao,
    note:data.note,
    buMenName:buMenName.value,

  }
  pmcOemNote(json).then(res=>{
    if(res.code == 200) {
      createMessage.success(res.message);
      applyViewShow.value = false;
      handleSuccess();
    }else{
      createMessage.error(res.message);
    }
  })
}
function resetEvent(e){
  console.log("--resetEvent:",e);
}


/**
 * 往前推6个月 并取那个月的1号
 */
function getSixMonthsAgoFirstDay() {
  // 获取当前日期
  const today = new Date();

  // 计算6个月前的年份和月份
  let year = today.getFullYear();
  let month = today.getMonth() - 6; // 月份从0开始计数

  // 处理月份小于0的情况（跨年份）
  if (month < 0) {
    year += Math.floor(month / 12);
    month = (month % 12 + 12) % 12;
  }

  // 创建6个月前1号的日期对象
  const sixMonthsAgo = new Date(year, month, 1);

  // 格式化日期为 yyyy-mm-dd 格式
  const formattedYear = sixMonthsAgo.getFullYear();
  const formattedMonth = String(sixMonthsAgo.getMonth() + 1).padStart(2, '0');
  const formattedDay = String(sixMonthsAgo.getDate()).padStart(2, '0');

  return `${formattedYear}-${formattedMonth}-${formattedDay}`;
}

function initArrDateStr(){
  let start=getSixMonthsAgoFirstDay();
  let now=new Date();
  let end=util.formatDate(now);
  return `${start},${end}`;
}

</script>
<style lang="less">
.vxe-cell{
  min-height: 26px !important;
  height: 26px !important;
  line-height: 12px;
}
</style>
